import 'package:casdon/modules/me/data/api/service_order_api.dart';
import 'package:casdon/modules/me/domain/states/service_order_state.dart';
import 'package:casdon/modules/me/domain/usecase/service_order_usecase.dart';
import 'package:casdon/modules/me/domain/usecase/service_reqId_usecase.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class ServiceOrderNotifier extends AutoDisposeAsyncNotifier<ServiceOrderState> {
  @override
  Future<ServiceOrderState> build() async {
    return _fetchData();
  }

  Future<void> refresh() async {
    try {
      final newState = await _fetchData();
      state = AsyncValue.data(newState);
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    }
  }

  Future<ServiceOrderState> _fetchData() async {
    final reqIdUsecase = ref.read(serviceReqidUsecaseProvider);
    final reqObjList = await reqIdUsecase.execute();
    if (reqObjList.isEmpty) {
      return ServiceOrderState(data: []);
    }
    final List<ServiceOrder> orderList = [];
    for (var req in reqObjList) {
      final orderUseCase = ref.read(serviceOrderUsecaseProvider);
      final orderData = await orderUseCase.execute(req.reqId);
      if (orderData == null) {
        continue;
      }
      if (orderData.entities.isNotEmpty) {
        orderList.add(orderData.entities.first);
      }
    }
    return ServiceOrderState(data: orderList);
  }
}

final serviceOrderNotifierProvider =
    AutoDisposeAsyncNotifierProvider<ServiceOrderNotifier, ServiceOrderState>(
      () => ServiceOrderNotifier(),
    );
